package com.example.musicrunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import com.example.musicrunner.media.PathManager;
import com.example.musicrunner.media.PlayListActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

 
public class MusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
 
    private MediaPlayer mplayer;
    private TextView songtitle;
    private TextView songCurrentDurationLabel;
    private TextView songTotalDurationLabel;
    
    private SeekBar progressBar;
    private int seekForwardTime = 5000; //ms
    private int seekBackwardTime = 5000; 
    private int count = 0;
    private Handler handler = new Handler();
    private PathManager path;
    private Utilities utils;

    // Player Buttons
    private ImageButton btnPlay;
    private ImageButton btnForward;
    private ImageButton btnBackward;
    private ImageButton btnNext;
    private ImageButton btnPrevious;
    private ImageButton btnPlaylist;
    private ImageButton btnRepeat;
    private ImageButton btnShuffle;
    private boolean isShuffle = false;
    private boolean isRepeat = false;
  
    
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        mplayer = new MediaPlayer();
        path = new PathManager();
        utils = new Utilities();
              
        songtitle = (TextView) findViewById(R.id.songTitle);
        songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
        songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
        
        // Player Buttons
        btnPlay =     (ImageButton) findViewById(R.id.btnPlay);
        btnForward =  (ImageButton) findViewById(R.id.btnForward);
        btnBackward = (ImageButton) findViewById(R.id.btnBackward);
        btnNext =     (ImageButton) findViewById(R.id.btnNext);
        btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
        btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
        btnRepeat =   (ImageButton) findViewById(R.id.btnRepeat);
        btnShuffle =  (ImageButton) findViewById(R.id.btnShuffle);
        progressBar = (SeekBar) findViewById(R.id.songProgressBar);
      
        // Listeners
        progressBar.setOnSeekBarChangeListener(this);  
        mplayer.setOnCompletionListener(this);  

        songsList = path.getPlayList();
 
        // Play 1st song default
        playSong(0);
        setupButton();
          

        /**
         * Play  a song and changes button to pause 
         * pause a song and changes button to play 
         * */
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if(mplayer.isPlaying()){
                    if(mplayer!=null){
                        mplayer.pause();
                        // Changing button image to play button
                        btnPlay.setImageResource(R.drawable.btn_play);
                    }
                } else {
                    if(mplayer!=null){
                        mplayer.start();
                        // Changing button image to pause button
                        btnPlay.setImageResource(R.drawable.btn_pause);
                    }
                }
            }
        });
 
        btnForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                int currentPosition = mplayer.getCurrentPosition();
                if(currentPosition + seekForwardTime <= mplayer.getDuration()){
                    // forward song
                    mplayer.seekTo(currentPosition + seekForwardTime);
                }else{
                    // forward to end position
                    mplayer.seekTo(mplayer.getDuration());
                }
            }
        });
 
        /**
         * Backward song to specified seconds
         * */
        btnBackward.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // get current song position
                int currentPosition = mplayer.getCurrentPosition();
                // check if seekBackward time is greater than 0 sec
                if(currentPosition - seekBackwardTime >= 0){
                    // forward song
                    mplayer.seekTo(currentPosition - seekBackwardTime);
                }else{
                    // backward to starting position
                    mplayer.seekTo(0);
                }
 
            }
        });
 
        /**
         * Plays next song by taking currentSongIndex + 1
         * */
        btnNext.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // check if next song is there or not
                if(count < (songsList.size() - 1)){
                    playSong(count + 1);
                    count = count + 1;
                }else{
                    // play first song
                    playSong(0);
                    count = 0;
                }
 
            }
        });
 
        /**
         * Plays previous song by count - 1
         * */
        btnPrevious.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                if(count > 0){
                    playSong(count - 1);
                    count = count - 1;
                }else{
                    // play last song
                    playSong(songsList.size() - 1);
                    count = songsList.size() - 1;
                }
 
            }
        });
        
        
        
        /**
         * Button Click event for Repeat button
         * Enables repeat flag to true
         * */
        btnRepeat.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                if(isRepeat){
                    isRepeat = false;
                    Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                    btnRepeat.setImageResource(R.drawable.btn_repeat);
                }else{
                    // make repeat to true
                    isRepeat = true;
                    Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                    // make shuffle to false
                    isShuffle = false;
                    btnRepeat.setImageResource(R.drawable.btn_repeat);
                    btnShuffle.setImageResource(R.drawable.btn_shuffle);
                }
            }
        });
 
        /**
         * Button Click event for Shuffle button
         * Enables shuffle flag to true
         * */
        btnShuffle.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                if(isShuffle){
                    isShuffle = false;
                    Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                    btnShuffle.setImageResource(R.drawable.btn_shuffle);
                }else{
                    // make repeat to true
                    isShuffle= true;
                    Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                    // make shuffle to false
                    isRepeat = false;
                    btnShuffle.setImageResource(R.drawable.btn_repeat);
                    btnRepeat.setImageResource(R.drawable.btn_repeat);
                }
            }
        });
 
        /**
         * Launches list activity which displays list of songs
         * */
        btnPlaylist.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
                startActivityForResult(i, 100);
            }
        });
 
    }
    
    
    private void setupButton() {
		Button button = (Button) findViewById(R.id.btB);
		button.setOnClickListener(new OnClickListener() {
		   @Override
		   public void onClick(View v) {
			
			 mplayer.stop();   
		     startActivity(new Intent(MusicPlayerActivity.this,ChangeActivity.class));	   		  
		  // finish();
		   }
		});
	   }
    /**
     * Receiving song index from playlist view
     * */
    @Override
    protected void onActivityResult(int requestCode,int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
             count = data.getExtras().getInt("songIndex");
             // play selected song
             playSong(count);
        }
 
    }
 
    /**
     * Function to play a song
     * */
    public void  playSong(int songIndex){
        try {
            mplayer.reset();
            mplayer.setDataSource(songsList.get(songIndex).get("songPath"));
            mplayer.prepare();
            mplayer.start();

            String songTitle = songsList.get(songIndex).get("songTitle");
            songtitle.setText(songTitle);

            btnPlay.setImageResource(R.drawable.btn_pause);

            progressBar.setProgress(0);
            progressBar.setMax(100);
 
            updateProgressBar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    //Update timer
    public void updateProgressBar() {
      handler.postDelayed(mUpdateTimeTask, 100);
    }   
 

   private Runnable mUpdateTimeTask = new Runnable() {
           public void run() {
               long totalDuration = mplayer.getDuration();
               long currentDuration = mplayer.getCurrentPosition();
 
               // Displaying Total Duration time
               songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
               // Displaying time completed playing
               songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
 
               // Updating progress bar
               int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
               progressBar.setProgress(progress);
               // Running this thread after 100 milliseconds
               handler.postDelayed(this, 100);
           }
        };
 
    /**
     *
     * */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
 
    }
 
    /**
     * When user starts moving the progress handler
     * */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
       // remove message Handler from updating progress bar
        handler.removeCallbacks(mUpdateTimeTask);
    }
 
    /**
     * When user stops moving the progress hanlder
     * */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
       handler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mplayer.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
        mplayer.seekTo(currentPosition);
        updateProgressBar();
    }
 
    /**
     * On Song Playing completed
     * */
    @Override
    public void onCompletion(MediaPlayer arg0) {
            // Play next song
            if(count < (songsList.size() - 1)){
                playSong(count + 1);
                count = count + 1;
            }else{
                // Play first song
                playSong(0);
                count = 0;
            }
     }
 
}